package com.hopu.day6_springboot.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Cookie工具类
 */
public class CookieUtil {

    public static final String ENCODE = "UTF-8";

    /**
     * Cookie保存
     * @param resp
     * @param name
     * @param value
     * @param maxAge
     */
    public static void save(HttpServletResponse resp,String name,String value,int maxAge) throws UnsupportedEncodingException {
        //创建Cookie时，对名称和值进行编码
        Cookie cookie = new Cookie(URLEncoder.encode(name,ENCODE),
                                    URLEncoder.encode(value,ENCODE));
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        resp.addCookie(cookie);
    }

    /**
     * 读取Cookie
     * @param req
     * @param name
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String read(HttpServletRequest req,String name) throws UnsupportedEncodingException {
        Cookie[] cookies = req.getCookies();
        for(Cookie cookie : cookies){
            //取名字和值时需要解码
            if(name.equals(URLDecoder.decode(cookie.getName(),ENCODE))){
                return URLDecoder.decode(cookie.getValue(),ENCODE);
            }
        }
        return null;
    }
}
